<template>
  <div>
      <MyFormCreate :clear-event="getTableList" v-model="searchForm" :rule="searchFormRules" :key="key">
        <template #field-unit="scope">
          <el-form-item>
            <unitSelectTreeScreen v-model="checkedUnit" :style="{ width: '100%' }" :placeholder="prompt?.unit"
              :teleported="false" clearable />
          </el-form-item>
        </template>
        <template #field-createdBy="scope">
          <el-form-item>
            <authorizeuserproject :project-id="usePageVariablesStore.getScreen()?.project?.id" :unity-id="checkedUnit"
              :teleported="false" @change="v => scope.data.model.callback(v)" v-model="searchForm.createdBy" clearable
              @clear="getTableList" :isid="1" :placeholder="prompt?.createdBy" :style="{ width: '100%' }" />
          </el-form-item>
        </template>
        <template #field-createdAt="scope">
          <el-form-item>
            <el-date-picker type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
              value-format="YYYY-MM-DD" placeholder="请选择创建时间" style="width: 100%" v-model="searchForm.createdAt"
              :teleported="false" @change="dateChange" />
          </el-form-item>
        </template>
        <el-button type="primary" @click="DebounceGetTableList">搜索</el-button>
        <sj-button custom-type="sinfo" @click="DebounceResetting">重置</sj-button>
      </MyFormCreate>
      <div>
        <el-button type="primary" :icon="Plus" @click="add">发起工单</el-button>
        <el-button type="danger" :disabled="!selectionData.length" @click="deletes()">批量删除</el-button>
      </div>
      <pure-table class="mt-5" :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)"
         @selection-change="selectionChange" :isShowPag="false">
        <template #workOrderStatus="{ row }">
          <span :style="{ color: WORKORDER_STATUSTEXT[row.workOrderStatus]?.color }">
            {{ isNullOrEmpty(WORKORDER_STATUSTEXT[row.workOrderStatus]?.label) }}
          </span>
        </template>
        <template #workOrderType="{ row }">
          {{ isNullOrEmpty(WORKORDER_TYPETEXT[row.workOrderType]?.label) }}
        </template>
        <template #waiting="{ row }">
          <el-space>
            {{ isNullOrEmpty(row.waitByName) }}
            <!-- {{ isNullOrEmpty( row.node?.[0]?.stepName ) }} -->
          </el-space>
        </template>
        <template #action="{ row }">
          <el-space>
            <sj-link custom-type="sblue" :underline="false" @click="handle(row)"
              v-if="row.workOrderStatus > 3">查看</sj-link>
            <sj-link v-auth="'business.workOrder.workOrder.deal'" custom-type="sblue" :underline="false"
              @click="handle(row)" v-else>处理</sj-link>
          </el-space>
        </template>
      </pure-table>
      <div class="mt-5">
        <el-pagination v-model:current-page="searchForm.page" v-model:page-size="searchForm.limit" background
          :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList" @current-change="getTableList" />
      </div>
   
    <!-- <workoderIfo
      v-model="centerDialogVisible"
      :id="workId"
      :closedlog="closedlog"
    ></workoderIfo> -->
  </div>
</template>
<script lang="ts" setup>
import { isNullOrEmpty, initPureTableConfig } from '@/utils/functions'
import { WORKORDER_TYPE, WORKORDER_TYPETEXT, WORKORDER_STATUSTEXT, WORKORDER_STATUS } from "@/constant/workorder-mangenment";
import authorizeuserproject from "@/components/select/authorizeuser/authorizeuserScreen.vue";
import workoderIfo from "./workorder-info.vue";
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import RePage from "@/components/RePage/index.vue";
import editForm from "./form.vue";
import { reactive, ref, h } from "vue";
import { PAGE_LAYOUT } from "@/constant";
import { Plus, Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getInspectionDetail, getInspectionDetailFacilities, deleteOrder } from "@/api/screen/work-management/index";
import { titles, defaultSearchFrom, prompt, defaultInfoFrom } from "./index";
import { addDialog, closeDialog } from "@/components/ReDialog";
import { deviceDetection, debounce } from "@pureadmin/utils";
import { usePageVariablesStoreHook } from "@/store/modules/pageVariables";
import unitSelectTreeScreen from '@/components/select/unitParentSelect/unitSelectTreeScreen.vue'
import { useDataDashboardThemeStoreHook } from "@/store/modules/data-dashboard-theme";
import { message } from "@/utils/message";
const props = defineProps({
  defaultSearch: {
    type: Object,
    default: null
  }
})
const usePageVariablesStore = ref(usePageVariablesStoreHook())
const centerDialogVisible = ref(false);
const searchForm = ref(defaultSearchFrom());
const key = ref(0);
const showInfo = ref();
const formRef = ref();
const formRefs = ref();
const checkedUnit = ref(null)
const tableData = reactive({
  data: [],
  total: 0
});

const workId = ref(null);
const searchFormRules = [

  {
    type: "input", field: "workOrderTitle", title: titles.workOrderTitle, value: null,
    props: {
      placeholder: prompt.workOrderTitle,
      clearable: true
    }
  },
  {
    type: "select", field: "workOrderType", title: titles.workOrderType, value: null,
    options: WORKORDER_TYPE,
    props: {
      placeholder: prompt.workOrderType,
      clearable: true, teleported: false
    }
  },
  {
    type: "select", field: "workOrderStatus", options: WORKORDER_STATUS, value: null,
    title: titles.workOrderStatus,
    props: {
      placeholder: prompt.workOrderStatus,
      clearable: true, teleported: false
    }
  },
  {
    type: "fieldComponent", field: "createdBy", title: titles.createdByName, value: null,
    props: {
      placeholder: prompt.createdByName,
      clearable: true
    }
  },
  {
    type: "fieldComponent", field: "createdAt", title: titles.createdAt, value: null,
    props: {
      placeholder: prompt.createdAt,
      clearable: true
    }
  },
  { type: "number", field: "page", title: "page", hidden: true },
  { type: "number", field: "limit", title: "limit", hidden: true }
];
const selectionData = ref([]);
const roleTableConfig = [
  { type: "selection", align: "left", fixed: 'left' },
  { prop: "id", label: titles.id, width: 100, fixed: 'left' },
  { prop: "unityName", label: titles.unityName, minWidth: 150 ,showOverflowTooltip:true },
  { prop: "projectName", label: titles.projectName, minWidth: 150 ,showOverflowTooltip:true },
  { prop: "workOrderTitle", label: titles.workOrderTitle, minWidth: 150 ,showOverflowTooltip:true },
  { prop: "createdByName", label: titles.createdByName, minWidth: 100 ,showOverflowTooltip:true },
  { slot: "workOrderType", label: titles.workOrderType, minWidth: 100 },
  { slot: "workOrderStatus", label: titles.workOrderStatus, minWidth: 100 },
  { slot: "waiting", label: titles.waiting, minWidth: 150 },
  { prop: "createdAt", label: titles.createdAt, minWidth: 180 },
  { slot: "action", label: titles.action, width: 80, fixed: "right" }
];
onMounted(() => {
  if (props.defaultSearch) {
    let searchRule = searchFormRules.map(item => item.field)
    for (const key in props.defaultSearch) {
      if (!searchRule.includes(key)) {
        searchFormRules.push({ type: '', field: key, title: key, hidden: true })
      }
      searchForm.value[key] = props.defaultSearch[key];
    }
    key.value = Math.floor(Math.random() * 1000)
  }
  if (useDataDashboardThemeStoreHook().dataDashboardType != 2) {
    searchFormRules.unshift({
      type: "fieldComponent", field: "unit", title: titles.unit, value: null,
      props: {
        placeholder: prompt.unit,
        clearable: true
      }
    })
    key.value = Math.floor(Math.random() * 1000)
  }
  getTableList();
});
// 获取列表数据
const getTableList = () => {
  getInspectionDetail(searchForm.value).then(res => {
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
    }
  });
};
// 重置搜索栏
const resetting = () => {
  //点击重置按键
  Object.assign(searchForm.value, defaultSearchFrom());
  key.value++;
  getTableList();
};
const dateChange = e => {
  searchForm.value.startTime = e[0];
  searchForm.value.endTime = e[1];
};
//关闭弹窗
const closedlog = e => {
  if (e == 1) {
    console.log(e, "是否要打开编辑")
    let row = {
      id: workId.value
    };
    edit(row);
  } else {
    centerDialogVisible.value = false;
  }
};
//编辑工单
function editOrderfunctions() {
  console.log('编辑工单');
  closedlog(1)
}
//处理工单
const handle = row => {
  workId.value = row.id;
  addDialog({
    title: `工单处理`,
    width: "800px",
    draggable: true,
    fullscreen: false,
    fullscreenIcon: true,
    hideFooter: true,
    closeOnClickModal: false,
    contentRenderer: () => h(workoderIfo, { ref: formRefs }),
    openAutoFocus({ options, index }) {
      formRefs.value.closeDialog((command) => {
        closeDialog(options, index, { command: command });
        console.log(command, "是否要打开编辑");

        if (command == "chexiao") {
          closedlog(1)
        } else {
          closedlog(0)
        }
      });
      options.props = {
        isLoading: true,
        id: row.id,
        editOrderfunction: editOrderfunctions
      };
      getInspectionDetailFacilities({ id: row.id })
        .then(res => {
          if (res.code == 200) {
            showInfo.value = res.result;
            options.props.formInline = res.result;
            options.props.isLoading = false;
            options.props.editOrderfunction = editOrderfunctions
          }
        })
        .finally(() => {
          options.props.isLoading = false;
        });
    }
  });
};

// 新增
const add = row => {
  if (usePageVariablesStore.value.getScreen()?.project?.id) {
    showInfo.value = {};
    openDialog("新增");
  } else {
    message('请先进入项目', { type: 'warning' });
  }

};
// 编辑
const edit = row => {
  showInfo.value = {};
  openDialog("编辑", row);
};
// 删除
const deletes = (row?) => {
  ElMessageBox.confirm(`确认删除${row ? "当前" : "选中的"}数据?`, "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteOrder({
      ids: row ? [row.id] : selectionData.value.map(item => item.id)
    }).then(res => {
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        getTableList();
      }
    });
  });
};
// 开启弹窗
const openDialog = (title, row?: any) => {
  addDialog({
    title: `${title}`,
    width: "800px",
    draggable: true,
    props: {
      isLoading: null,
      formInline: defaultInfoFrom(),
      edittype: title
    },
    fullscreen: false,
    fullscreenIcon: true,
    closeOnClickModal: false,
    hideFooter: true,
    contentRenderer: () => h(editForm, { ref: formRef }),
    openAutoFocus({ options, index }) {
      formRef.value.closeDialog((command = "sure") => {
        closeDialog(options, index, { command: command });
        if (command == "sure") {
          DebounceGetTableList();
        }
      });
      if (row) {
        options.props = {
          isLoading: true,
          formInline: defaultInfoFrom(),
          edittype: title
        };
        getInspectionDetailFacilities({ id: row.id })
          .then(res => {
            if (res.code == 200) {
              showInfo.value = res.result;
              options.props.formInline = res.result.workerOrderInfo;
            }
          })
          .finally(() => {
            options.props.isLoading = false;
          });
      } else {
        options.props = {
          isLoading: false,
          formInline: defaultInfoFrom(),
          edittype: title
        };
        options.props.formInline.projectId = usePageVariablesStore.value.getScreen()?.project?.id
      }
    }
  });
};
const selectionChange = data => {
  selectionData.value = data;
};
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
</script>
<style lang="scss" scoped></style>
